<template>
  <div class="content">
    <pageHeaderNew title="我的文档"></pageHeaderNew>
    <div class="search-box">
      <div>
        <a-space>
          <a-input-search
            :style="{ width: '420px' }"
            placeholder="输入名称进行搜索"
            style="margin-bottom: 8px; max-width: 240px"
            v-model="searchKey"
          />
        </a-space>
      </div>

      <div>
        <a-space>
          <a-button type="primary" @click="openFolderModal">
            <template #icon>
              <icon-plus />
            </template>
            <template #default>新增文件夹 </template>
          </a-button>
          <a-button status="success" @click="openUploadModal">
            <template #icon>
              <icon-plus />
            </template>
            <template #default>上传</template>
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="table-box">
      <!-- <a-tree
        :data="treeData"
        style="margin-top: 30px"
        :fieldNames="{
          key: 'id',
          title: 'storeName',
          icon: ''
        }"
      >
        <template #title="nodeData">
          <template
            v-if="((index = getMatchIndex(nodeData?.title)), index < 0)"
            >{{ nodeData?.title }}</template
          >
          <span v-else>
            {{ nodeData?.title?.substr(0, index) }}
            <span style="color: var(--color-primary-light-4)">
              {{ nodeData?.title?.substr(index, searchKey.length) }} </span
            >{{ nodeData?.title?.substr(index + searchKey.length) }}
          </span>
        </template>
        <template #extra="nodeData">
          <div
            v-if="nodeData.children && nodeData.storeName !== '根目录'"
            style="
              position: absolute;
              right: 8px;
              font-size: 12px;
              top: 10px;
              color: #3370ff;
            "
          >
            <a-button type="text" @click="openFolderModal">新增文件夹</a-button>
            <a-button type="text" @click="openUploadModal">上传文件</a-button>
            <a-button type="text">修改</a-button>
            <a-button type="text" status="danger">删除文件夹</a-button>
          </div>
          <div
            v-else-if="nodeData.children && nodeData.storeName == '根目录'"
            style="
              position: absolute;
              right: 8px;``
              font-size: 12px;
              top: 10px;
              color: #3370ff;
            "
          >
            <a-button type="text" @click="openFolderModal">新增文件夹</a-button>
            <a-button type="text" @click="openUploadModal">上传文件</a-button>
          </div>
          <div
            v-if="!nodeData.children"
            style="
              position: absolute;
              right: 8px;
              font-size: 12px;
              top: 10px;
              color: #3370ff;
            "
          >
            <a-button type="text">预览</a-button>
            <a-button type="text" status="danger">删除文件</a-button>
          </div>
        </template>
      </a-tree> -->
      <!-- <TableTurn
        style="margin: 0 10px; margin-right: 30px"
        :tableData="getTableData"
        :args="args"
        ref="tableRef"
        :isShowPagination="false"
      >

      </TableTurn> -->
      <a-table
        :pagination="false"
        :data="getTreeData"
        show-empty-tree
        style="margin-top: 20px"
        rowKey="id"
      >
        <template #expand-icon="{ expanded }">
          <icon-down v-show="expanded" />
          <icon-right v-show="!expanded" />
        </template>
        <template #columns>
          <!-- <a-table-column :width="60" title="序号" fixed="left">
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column> -->
          <a-table-column :width="200" dataIndex="storeName" title="序号">
            <template #cell="{ record }">
              <icon-font
                :type="
                  !record.downloadPath ? 'icon-wenjianjia' : 'icon-wenjian'
                "
                :size="20"
                style="cursor: pointer; margin-left: 10px"
              />
            </template>
          </a-table-column>

          <a-table-column :width="200" dataIndex="storeName" title="名称">
            <template #cell="{ record }">
              <a-input
                v-if="isShow && record.id === setFileData.id"
                :style="{ width: '320px' }"
                placeholder="Disabled status"
                v-model="setFileName"
                :error="isError"
                @change="changeFileName"
              />
              <div
                v-else
                style="
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  overflow: hidden;
                "
              >
                {{ record.storeName.split('.')[0] }}
              </div></template
            >
          </a-table-column>
          <!-- <a-table-column :width="200" title="文件类型">
            <template #cell="{record}"> {{ record.storeName.split('.')[1] }}</template>
 -->
          <a-table-column :width="200" title="文件类型">
            <template #cell="{ record }">
              {{
                record.fileName
                  ? `.${record.storeName.split('.')[1]}`
                  : '文件夹'
              }}</template
            >
          </a-table-column>

          <a-table-column :width="200" title="创建人">
            <template #cell> {{ '--' }}</template>
          </a-table-column>
          <a-table-column :width="200" title="操作	">
            <template #cell="{ record }">
              <a-space v-if="record.fileName">
                <a-tooltip content="分享">
                  <icon-font
                    type="icon-fenxiangfangshi"
                    :size="19"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer'
                    }"
                    @click="goShare(record)"
                  />
                </a-tooltip>
                <a-tooltip content="删除文件">
                  <a-popconfirm
                    content="确认删除文件?"
                    type="error"
                    @ok="delFile(record)"
                  >
                    <IconFont
                      type="icon-delete"
                      :size="26"
                      :style="{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }"
                    />
                  </a-popconfirm>
                </a-tooltip>
                <a-tooltip content="更多操作">
                  <a-dropdown>
                    <icon-font
                      type="icon-more-def"
                      :size="26"
                      :style="{
                        cursor: 'pointer'
                      }"
                    />
                    <template #content>
                      <a-doption @click="openTabs(record)"
                        ><template #icon>
                          <icon-font
                            type="icon-xinbiaoqianyedakai"
                            :size="15"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >新标签页打开</a-doption
                      >
                      <a-doption @click="copy(record)">
                        <template #icon>
                          <icon-font
                            type="icon-lianjie"
                            :size="18"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >复制链接</a-doption
                      >
                      <a-doption @click="goRename(record)"
                        ><template #icon>
                          <icon-font
                            type="icon-zhongmingming"
                            :size="16"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >重命名</a-doption
                      >
                      <a-doption @click="setPreview(record)">预览</a-doption>
                      <a-doption @click="SetupCollect(record)"
                        ><template #icon>
                          <icon-font
                            type="icon-shoucang"
                            :size="18"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >收藏</a-doption
                      >
                      <a-doption @click="SetupSharing(record)"
                        ><template #icon>
                          <icon-font
                            type="icon-gongxiang"
                            :size="18"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >{{
                          record.shareState === 1 ? '发起共享' : '取消共享'
                        }}</a-doption
                      >
                    </template>
                  </a-dropdown>
                </a-tooltip>
                <!-- <a-popconfirm
                  content="确定要删除该文件?"
                  type="error"
                  @ok="delFile(record)"
                >
                  <a-button type="text" status="danger">删除</a-button>
                </a-popconfirm> -->
              </a-space>
              <div v-else type="text" @click="setDocument(record)">
                {{ '--' }}
              </div>
            </template>
          </a-table-column></template
        >
      </a-table>
    </div>
  </div>

  <UploadModal
    :userId="userInfo.id"
    ref="uploadRef"
    @hide="setHide"
  ></UploadModal>
  <FolderModal
    v-if="modalVisible"
    v-model:visible="modalVisible"
    :data="data"
    :tree="getTreeData"
    @addDocumentEmit="setDocument"
  ></FolderModal>
  <FilePreview
    v-model:visible="PreviewModelVisible"
    ref="previewFileRef"
    v-if="previewFile.fileShow"
    :file="previewFile.fileMessage"
  >
  </FilePreview>
  <ShareModel
    v-if="shareModelVisible"
    v-model:visible="shareModelVisible"
    :sharingInfo="SharingInfo"
  ></ShareModel>
</template>

<script lang="ts" setup>
import {
  PostStorageDisk,
  getFileDelong,
  deleteFile,
  putShareState,
  postFileCollect,
  putFileName
} from '@/apis/document/documentCenter/index';
import { Message } from '@arco-design/web-vue';
import useClipboard from 'vue-clipboard3';
import UploadModal from './UploadModal.vue';
import FolderModal from './FolderModal.vue';
import ShareModel from '../components/share.vue';

const { toClipboard } = useClipboard();

const router = useRouter();
const previewFile = reactive({
  fileShow: false,
  fileMessage: {
    id: '',
    fileName: '',
    downloadUrl: ''
  }
});
const shareModelVisible = ref(false);
const PreviewModelVisible = ref(false);
const expandedKeys = ref([]);
const data = ref({});
const modalVisible = ref(false);
const uploadRef = ref();
const searchKey = ref('');
const userInfo = JSON.parse(localStorage.getItem('userInfo') as any);
const previewFileRef = ref();
const getTreeData = ref<any>([]);
const SharingInfo = ref({});

function getMatchIndex(title: any) {
  if (!searchKey.value) return -1;
  return title.toLowerCase().indexOf(searchKey.value.toLowerCase());
}

const openUploadModal = () => {
  uploadRef.value.visible = true;
};

// const expand = (val: any, res: any) => {
//   console.log(1, val, res);
//   if (!res.file) return;
//   if (res.first) return;
//   res.first = true;
//   res.file.forEach((item: any) => {
//     res.children.push({ ...item, storeName: item.useFileName, type: 1 });
//   });
// };

const openFolderModal = () => {
  modalVisible.value = true;
};

const tree = (data: any) => {
  data.forEach((element: any) => {
    element.children = element.children || [];
    if (element.children) tree(element.children);
  });
  return data;
};

const setTreeData = (data: any) => {
  data.forEach((item: any) => {
    if (item.file) {
      item.file.forEach((ele: any) => {
        item.children.push({ ...ele, storeName: ele.useFileName, type: 1 });
      });
    }
    if (item.children) setTreeData(item.children);
  });
  return data;
};

const getTableData = async () => {
  try {
    const res = await getFileDelong({ userId: userInfo.id });
    getTreeData.value = [{ ...res }];
    setTreeData(getTreeData.value);
    // console.log(3, setTreeData(getTreeData.value));
  } catch (err: unknown) {
    console.log(err);
  }
};
getTableData();

const setDocument = async (val: any) => {
  try {
    console.log(val);
    if (!val.id) await PostStorageDisk({ ...val });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const setPreview = (val: any) => {
  previewFile.fileMessage.id = val.id;
  previewFile.fileMessage.fileName = val.fileName;
  previewFile.fileMessage.downloadUrl = val.downloadPath;
  previewFile.fileShow = true;
  PreviewModelVisible.value = true;
};

const delFile = async (res: any) => {
  try {
    await deleteFile({ id: res.id, type: 0 });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const SetupSharing = async (val: any) => {
  try {
    await putShareState({ id: val.id });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const setHide = (res: boolean) => {
  if (res) getTableData();
  expandedKeys.value = [];
};

const SetupCollect = async (record: any) => {
  try {
    await postFileCollect({ userId: userInfo.id, fileId: record.id });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const copy = async (res) => {
  try {
    await toClipboard(res.downloadPath);
    Message.success('复制成功');
  } catch (err: unknown) {
    console.log(err);
  }
};
const setFileName = ref();
const isShow = ref(false);
const fileType = ref();
const setFileData = ref();
const isError = ref(false);
const goRename = async (res: any) => {
  setFileName.value = res.storeName.split('.')[0];
  fileType.value = res.storeName.split('.')[1];
  setFileData.value = res;
  isShow.value = true;
  console.log(setFileData.value, fileType.value, setFileName.value);
};

const changeFileName = async (e: string) => {
  try {
    if (setFileName.value === '') {
      isError.value = true;
      return;
    }
    await putFileName({
      useFileName: `${setFileName.value}.${fileType.value}`,
      id: setFileData.value.id
    });
    getTableData();
    setFileName.value = undefined;
    fileType.value = undefined;
    setFileData.value = undefined;
    isShow.value = false;
    isError.value = false;
  } catch (err: unknown) {
    console.log(err);
  }
};

const openTabs = (res) => {
  router.push({ name: 'FileTabsPage', query: { url: res.downloadPath } });
};

const goShare = (res: any) => {
  shareModelVisible.value = true;
  SharingInfo.value = res;
};
</script>

<style scoped lang="less">
.content {
  padding: 10px;
  height: 100%;
  width: 100%;
}

.search-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 96%;
  margin: 10px;
}

:deep(.arco-table-tr) {
  height: 40px;
}
:deep(.arco-table-th) {
  font-weight: bold;
  // font-size: 13px;
}
</style>
